package com.example.foodiemoments.ui.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.foodiemoments.databinding.ItemRecipeBinding
import com.example.foodiemoments.ui.models.Recipe

class RecipeAdapter : ListAdapter<Recipe, RecipeAdapter.ViewHolder>(RecipeDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemRecipeBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class ViewHolder(private val binding: ItemRecipeBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(recipe: Recipe) {
            binding.apply {
                tvTitle.text = recipe.title
                tvAuthor.text = recipe.author
                tvDescription.text = recipe.description
                tvLikeCount.text = recipe.likeCount.toString()
                tvCommentCount.text = recipe.commentCount.toString()
                tvCollectCount.text = recipe.collectCount.toString()

                ivCover.setImageResource(recipe.coverImage)
                ivAuthorAvatar.setImageResource(recipe.authorAvatar)

                // 点击事件
                root.setOnClickListener {
                    // TODO: 跳转到详情页
                }
            }
        }
    }

    class RecipeDiffCallback : DiffUtil.ItemCallback<Recipe>() {
        override fun areItemsTheSame(oldItem: Recipe, newItem: Recipe):
                Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Recipe, newItem: Recipe): Boolean {
            return oldItem == newItem
        }
    }
}
